@using DNA.Mvc.Controllers;
@{
    Layout = "";
    var context = WebSiteContext.Current;
    var folderPath = context.ApplicationPath + context.Web.WebFolder;
}
<div id="dna_fileExplorer" style="width:500px;">
    @{
        Ajax.Dna().Toolbar()
           .Name("WebResToolbar")
        .Buttons(buttons =>
        {
            if (context.IsAuthorized<WebFilesController>("CreatePath"))
            {
                buttons.AddButton(Html.Global("FileExplorer_AddRootFolder"), "_showAddFolderDlg(true);").ImageIcons(Url.Content("~/content/images/icon_addrootfolder_16.png")).Name("AddRootFolderButton");
                buttons.AddButton(Html.Global("FileExplorer_AddSubFolder"), "_showAddFolderDlg(false);").ImageIcons(Url.Content("~/content/images/icon_addsubfolder_16.png")).Name("AddSubFolderButton");
            }

            if (context.IsAuthorized<WebFilesController>("Delete"))
            {
                buttons.AddButton(Html.Global("RES_DELETEFOLDER"), "_deleteSelectedFolder();").ImageIcons(Url.Content("~/content/images/icon_delete_folder_16.png"));
                buttons.AddSpliter();
                buttons.AddButton(Html.Global("RES_DELETEFILE"), "_deleteSelectedFile();").ImageIcons(Url.Content("~/content/images/icon_delete_file_16.png"));
            }
            buttons.AddSpliter();
            buttons.AddButton(Html.Global("RES_HELP"), "window.open(\"" + Url.Help(3) + "\");").ImageIcons(Url.Content("~/content/images/icon_help_16.png"));
        })
            .Render();
        if (context.IsAuthorized<WebFilesController>("CreatePath"))
        {
            Ajax.Dna().Dialog(Html.Global("FileExplorer_EnterNewFolderName"))
                .Name("AddFolderDlg")
                .Options(opts =>
                {
                    opts.AutoOpen = false;
                    opts.bgiFrame = true;
                    opts.ShowModal = true;
                    opts.IsResizable = false;
                })
                .Buttons(dlgButtons =>
                {
                    dlgButtons.Add("Save", "_addNewFolder();");
                    dlgButtons.AddClose();
                })
                .Body(@<text>
        <dl style="margin: 0px;">
            <dd class="ui-helper-reset">
                Enter the new folder name</dd>
            <dd class="ui-helper-reset">
                @Ajax.Dna().TextBox("NewFolderName").Width(260).Value("NewFolder").GetHtml()
            </dd>
        </dl>
        </text>)
                .Render();
                }
        }
    <table style="width: 100%">
        <tr>
            <td style="vertical-align:top;" colspan="2">
                @(
 Ajax.Dna().TextBox("txtAddress")
                        .Width(900)
                        .Options(opts =>
                        {
                            opts.Clearable = false;
                            opts.ReadOnly = true;
                        })
                                .Value(folderPath)
                        .IconImageUrl(Url.Content("~/content/images/folder.gif"))
                        .GetHtml()
                        )
            </td>
        </tr>
        <tr>
            <td id="dna_fileExplorer_resizer" style="width: 250px;vertical-align:top;">
                @(Ajax.Dna().TreeView()
                       .Name("ExplorerFoldersTreeView")
                       .HtmlAttributes(new { style = "width:250px;height:400px;border:1px solid #cccccc;padding:5px;overflow:auto;margin:0px;" })
                       .Options(opts =>
                       {
                           opts.EnableDropAndDrag = true;
                           opts.OnNodeDropped = "_moveFolder(ui.node,ui.targetNode);";
                           opts.OnNodeSelected = "var _path=$(\">.d-treenode-content\",node).find(\".d-treenode-value\").val();$(\"#txtAddress\").val(_path); $(\"#filelistview\").load(\"" + Url.Action("ListView", "WebFiles", new { Area = "" }) + "\",{path:_path});";
                           opts.OnNodePopulate = (new System.Text.StringBuilder())
                                                                  .Append("var $n = $(node);")
                                                                  .Append("$n.addClass(\"d-treenode-loading\");")
                                                                  .Append("var _url = $(\">.d-treenode-content\", $n).find(\".d-treenode-value\").val();")
                                                                  .Append("$(\"#ExplorerFoldersTreeView\").dtree(\"loadNodes\", \"" + Url.Action("GetPaths", "WebFiles", new { Area = "" }) + "\", \"GET\", {url:_url}, $n);")
                                                                  .Append("$n.removeClass(\"d-treenode-hasChildren\");")
                                                                  .ToString();
                           opts.OnNodeLoaded = "if (node) {$(node).removeClass(\"d-treenode-loading\");}";
                       })
                   .ClientBind(Url.Action("GetPaths", "WebFiles", new { Area = "", url = folderPath }))
                   .ClientNodeTemplate(@<text>
                     <li {{if Value}} class="d-treenode-hasChildren" {{/if}}>
                       <a href="javascript:void(0);" rel="@Url.Action("GetPaths", "WebFiles", new { Area = "" })?url=${Value}" title="${ToolTip}" {{if Target}} target="${Target}" {{/if}}>
                          {{if ImageUrl}}  <img src="${ImageUrl}" class="d-treenode-img" alt="${Text}" /> {{/if}}
                          {{if Value}} <input type="hidden" class="d-treenode-value" value="${Value}" /> {{/if}}
                          <span class="d-treenode-text">${Text}</span>
                       </a>
                     </li>
                    </text>)
                   .GetHtml()
                )
                <fieldset class="ui-corner-all" style="text-align: center; height: 166px;">
                    <legend style="color: #000000;">Preview</legend>
                    <img src="" id="previewImg" alt="" style="display: none;" />
                </fieldset>
            </td>
            <td style="vertical-align:top;" id="filelistview">
                @{ Html.RenderAction("ListView", "WebFiles", new { path = folderPath }); }
            </td>
        </tr>
        <tr>
            <td colspan="2">
                @{ 
                    Ajax.Dna().TextBox("txtFileExplorerStatus")
                       .Width(900)
                       .Options(opts =>
                       {
                           opts.Clearable = false;
                           opts.ReadOnly = true;
                       })
                       .IconImageUrl(Url.Content("~/content/images/icon_attach_16.png"))
                       .Render(); 
                }
            </td>
        </tr>
    </table>
</div>
<input type="hidden" id="addRootIdentity" value="true" />
<input type="hidden" id="websharedRoot" value="@folderPath" />
<script type="text/x-jquery-tmpl" id="explorerFolderTreeClientNodeTmpl">
<li>
   <a href="javascript:void(0);" rel="@Url.Action("GetPaths", "WebFiles", new { Area = "" })?url=${Url}" title="${Url}" >
        <img src="@Url.Content("~/content/images/folder.gif")" class="d-treenode-img" alt="${Name}" />
        <input type="hidden" class="d-treenode-value" value="${Url}" />
        <span class="d-treenode-text">${Name}</span>
   </a>
</li>
</script>
<script type="text/javascript">
    function _deleteSelectedFile() {
        var _row=$("#WebFilesGrid").dgrid("option", "selectedRow")
        
        if (_row) {
            var $row = $(_row).find("input[type='hidden']"),
            _filename = $row.val(), _confirmStr='@Html.Global("RES_CONFIRMFILEDELETE")';
            $dna.confirm('@Html.Global("RES_QUESTION")', _confirmStr.replace("{0}",_filename) ,function(){
                $.ajax({
                            url: _filename,
                            type: "DELETE",
                            success: function (response) { 
                                 if (response!="OK"){
                                      $dna.showDlg("Error",response);
                                     return;
                                 }
                                 $("#WebFilesGrid_pager").pager("reload"); 
                            }
                        });
            });
        }
    }
    
    function _moveFolder(_srcElement,_targetElement){
      var _srcUrl=$(">.d-treenode-content",_srcElement).find(".d-treenode-value").val(),
      _targetUrl=$(">.d-treenode-content",_targetElement).find(".d-treenode-value").val()+"/"+$(">.d-treenode-content",_srcElement).find(".d-treenode-text").first().text();


      $.ajax({
         type:"POST",
         url:'@Url.Action("Move", "WebFiles", new { Area = "" })',
         data:{sourceUri:_srcUrl,destination:_targetUrl},
          success:function(data){
            $(">.d-treenode-content",_srcElement).find(".d-treenode-value").val(_targetUrl);
          }
      });
    }

    function _showAddFolderDlg(_isroot)
    {
       $("#addRootIdentity").val(_isroot);
       $("#AddFolderDlg").dialog("open");
    }

    function _addNewFolder()
    {
        if ($("#NewFolderName").val()) {
           var destUrl=$("#txtAddress").val();
           if ($("#addRootIdentity").val()=="true") 
              destUrl=$("#websharedRoot").val();
           else
              destUrl+="/";

          destUrl+= $("#NewFolderName").val();

          if (_getFolderNodeByValue(destUrl).length) {
             alert("The path is exists!");
             $("#NewFolderName").focus();
             return;
          };

          $.ajax({
             type:"POST",
             url:'@Url.Action("CreatePath", "WebFiles", new { Area = "" })',
             data:{destination:destUrl},
             success:function(data){
                $("#ExplorerFoldersTreeView").dtree($("#addRootIdentity").val()=="true" ? "addRoot":"addNode", $("#explorerFolderTreeClientNodeTmpl").tmpl(data));
             }
          });
           $("#AddFolderDlg").dialog("close");
        }
        else {
           $("#NewFolderName").focus();
        }
    }

    function _getFolderNodeByValue(_val)  {
       var node=$("#ExplorerFoldersTreeView").find(".d-treenode-value:input[value='"+_val+"']");
       if (node) return node.closest(".d-treenode");

    }

    function _deleteSelectedFolder() {
       var _folder=$("#txtAddress").val();
       if (_folder) {
          var _confirmStr='@Html.Global("RES_CONFIRMFOLDERDELETE")';
          $dna.confirm('@Html.Global("RES_INFO")', _confirmStr.replace("{0}",_folder),function(){
                 $.ajax({
                    url: _folder,
                    type: "DELETE",
                    success: function (response) {
                       if (response!="OK"){
                          $dna.showDlg("Error",response);
                          return;
                       }
                    
                       var _folderNode=_getFolderNodeByValue(_folder);
                       if (_folderNode) {
                           var firstSibling=_folderNode.siblings().first();
                           var $selNode=null;
                           if (firstSibling.length) $selNode=firstSibling; else   {
                              if ( _folderNode.closest(".d-treenode").length>0)
                                 $selNode=_folderNode.parent().closest(".d-treenode");
                           } 
                            if ($selNode) $("#ExplorerFoldersTreeView").dtree("select",$selNode);
                           $(_folderNode).remove();
                          
                       }
                    }
                });
          });
       } 
    }

</script>
@Html.StartupScripts()